package com.tech.connect.zhaorencai;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.ksy.common.model.City;
import com.ksy.common.utils.BaseAdapter;
import com.ksy.common.utils.BaseHolder;
import com.ksy.common.utils.LogTool;
import com.ksy.map.GDMapView;
import com.ksy.map.LatLngProxy;
import com.tech.connect.R;
import com.tech.connect.activity.CityChooseActivity;
import com.tech.connect.activity.SearchActivity;
import com.tech.connect.api.BaseEntityOb;
import com.tech.connect.api.CurrentInfo;
import com.tech.connect.api.JianLiHttp;
import com.tech.connect.fragment.BaseFragment;
import com.tech.connect.model.CatChoose;
import com.tech.connect.model.ItemCatSub;
import com.tech.connect.model.ItemJianLi;
import com.tech.connect.model.KeyWord;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RenCaiHomeFragment extends BaseFragment {

    private GDMapView mapView;
    private ArrayList<ItemJianLi> allList = new ArrayList<>();
    private List<KeyWord> allKeyWordList = new ArrayList<>();
    private RenCaiMainFragment.TitleListener titleListener;
    private RecyclerView recycler;
    private BaseAdapter<KeyWord, BaseHolder> adapter;
    private TextView tvCity;
    private TextView tvCat;
    private TextView tvOptions;
    private Map<String, Object> map = new HashMap<>();
    private City selectCity;
    private AMapLocationClient locationClient;
    private LatLng currentLocation;
    private AMap aMap;
    private ItemCatSub salary;
    private ItemCatSub education;
    private ItemCatSub work;
    private ItemCatSub userStatus;

    @Override
    public View onCreateView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_rencai_home, null);
        return view;
    }

    @Override
    protected boolean isShowHeadBar() {
        return true;
    }

    @Override
    protected boolean isFullStateBar() {
        return true;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getHeadBar().setLeftIcon(R.drawable.icon_back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.onBackPressed();
            }
        }).setTitle("连合作", 0, R.drawable.icon_arrow_down_white)
                .setTitleClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (titleListener != null) {
                            titleListener.onFragmentTitleClick();
                        }
                    }
                }).setRightIcon(R.drawable.icon_search, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2Activity(SearchActivity.class);
            }
        });

        initView(view);
        initLocation();
        loadKeyWord();
    }

    private void initLocation() {
        locationClient = new AMapLocationClient(activity);
        AMapLocationClientOption locationOption = new AMapLocationClientOption();
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        locationOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        locationOption.setHttpTimeOut(30 * 1000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        locationOption.setInterval(10 * 60 * 1000);//可选，设置定位间隔。默认为2秒
        locationOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        locationOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        locationOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        locationOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        locationOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        locationOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        locationClient.setLocationOption(locationOption);
        AMapLocationListener locationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation location) {
                LogTool.w("AMapLocation " + location);
                if (location != null && location.getErrorCode() == 0) {
                    currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                    CurrentInfo.getUserInfo().lat = location.getLatitude();
                    CurrentInfo.getUserInfo().lng = location.getLongitude();
                    CurrentInfo.getUserInfo().provinceName = location.getProvince();
                    CurrentInfo.getUserInfo().cityName = location.getCity();
                    CurrentInfo.getUserInfo().district = location.getDistrict();
                    CurrentInfo.getUserInfo().address = location.getAddress();
                } else {
                    currentLocation = null;
                }
//                tvCity.setText(CurrentInfo.getUserInfo().cityName);
                if (mapView != null && currentLocation != null) {
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 12));
                }
                loadJianLi();
            }
        };
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
        locationClient.startLocation();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getView() != null) {
            mapView = getView().findViewById(R.id.mapView);
            if (mapView != null) {
                mapView.onCreate(savedInstanceState);
                mapView.setMarkerClickListener(new GDMapView.MarkerClickListener() {
                    @Override
                    public void onMarkerClick(Marker marker) {
                        Object object = marker.getObject();
                        if (object != null && object instanceof ItemJianLi) {
                            ItemJianLi item = (ItemJianLi) object;
                            showLog(item.toString());
                            Intent intent = new Intent(activity, RenCaiViewActivity.class);
                            int i = allList.indexOf(item);
                            intent.putExtra("index", i);
                            intent.putExtra("dataList", allList);
                            jump2Activity(intent);

                        }
                    }
                });
                aMap = mapView.getMap();
                aMap.getUiSettings().setZoomControlsEnabled(false);
                aMap.getUiSettings().setMyLocationButtonEnabled(false);
                aMap.setMyLocationEnabled(false);
                LatLng lng = new LatLng(CurrentInfo.getUserInfo().lat, CurrentInfo.getUserInfo().lng);
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lng, 10));
            }
        }
    }

    private void initView(View view) {
        recycler = view.findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));


        tvCity = view.findViewById(R.id.tvCity);
//        tvCity.setText(CurrentInfo.getUserInfo().cityName);
        tvCity.setText("切换城市");
        view.findViewById(R.id.vCity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2Activity(CityChooseActivity.class, 10001);
            }
        });
        tvCat = view.findViewById(R.id.tvCat);
        view.findViewById(R.id.vCat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2Activity(RenCaiCatChooseActivity.class, 10002);
            }
        });
        tvOptions = view.findViewById(R.id.tvOptions);
        view.findViewById(R.id.vOptions).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, RenCaiOptionsChooseActivity.class);
                intent.putExtra("salary", salary);
                intent.putExtra("education", education);
                intent.putExtra("work", work);
                intent.putExtra("userStatus", userStatus);
                jump2Activity(intent, 10003);
            }
        });
        TextView tvPublish = view.findViewById(R.id.tvPublish);
        tvPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2Activity(PublishJianLiActivity.class, 10004);
            }
        });
    }

    private void loadKeyWord() {
        JianLiHttp.keyWord(new BaseEntityOb<List<KeyWord>>() {
            @Override
            public void onDataDeal(boolean isSuccess, List<KeyWord> data, String msg) {
                iniKeyWordAdapter(data);
            }
        });
    }

    private void loadJianLi() {
        //以下必须
        map.put("lat", CurrentInfo.getUserInfo().lat);
        map.put("lng", CurrentInfo.getUserInfo().lng);
        JianLiHttp.list(map, new BaseEntityOb<List<ItemJianLi>>() {
            @Override
            public void onDataDeal(boolean isSuccess, List<ItemJianLi> data, String msg) {
                iniAdapter(data);
            }
        });
    }

    private void iniAdapter(List<ItemJianLi> data) {
        allList.clear();
        if (data != null) {
            allList.addAll(data);
        }
        if (mapView != null) {
            aMap = mapView.getMap();
            aMap.clear();
            aMap.getUiSettings().setZoomControlsEnabled(false);
            aMap.getUiSettings().setMyLocationButtonEnabled(false);
            aMap.setMyLocationEnabled(false);
            List<LatLngProxy> latLngProxies = new ArrayList<>();
            latLngProxies.addAll(allList);
            mapView.showMarkers(latLngProxies);
            if (selectCity != null) {
                LatLng lng = new LatLng(selectCity.lat, selectCity.lng);
                aMap.moveCamera(CameraUpdateFactory.newLatLng(lng));
            }
        }


    }

    private void iniKeyWordAdapter(List<KeyWord> data) {
        allKeyWordList.clear();
        if (data != null) {
            allKeyWordList.addAll(data);
        }
        if (adapter == null) {
            adapter = new BaseAdapter<KeyWord, BaseHolder>(R.layout.item_layou_keyword, allKeyWordList) {
                @Override
                protected void convert(BaseHolder helper, int position) {
                    KeyWord keyWord = allKeyWordList.get(position);
                    TextView tv = helper.getView(R.id.tv);
                    tv.setText(keyWord.name);
                }
            };
            adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {

                }
            });
            recycler.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Activity.RESULT_OK && intent != null) {
            if (requestCode == 10001) {
                //城市切换
                Serializable data = intent.getSerializableExtra("data");
                if (data != null && data instanceof City) {
                    selectCity = (City) data;
                    tvCity.setText(selectCity.name);
                    map.put("cityCode", selectCity.id);
                    loadJianLi();
                }
            } else if (requestCode == 10002) {
                //职业切换
                Serializable dataCat = intent.getSerializableExtra("mainCat");
                Serializable dataSub = intent.getSerializableExtra("subCat");
                if (dataCat != null && dataCat instanceof CatChoose) {
                    CatChoose catChoose = (CatChoose) dataSub;
                    map.put("category", catChoose.id);
                    tvCat.setText(catChoose.name);
                    loadJianLi();
                }
            } else if (requestCode == 10003) {
                //条件切换
                Serializable salarySer = intent.getSerializableExtra("salary");
                Serializable educationSer = intent.getSerializableExtra("education");
                Serializable workSer = intent.getSerializableExtra("work");
                Serializable userStatusSer = intent.getSerializableExtra("userStatus");
                if (salarySer != null && salarySer instanceof ItemCatSub) {
                    salary = (ItemCatSub) salarySer;
                    map.put("salary", salary.value);
                }
                if (educationSer != null && educationSer instanceof ItemCatSub) {
                    education = (ItemCatSub) educationSer;
                    map.put("education", education.value);
                }
                if (workSer != null && workSer instanceof ItemCatSub) {
                    work = (ItemCatSub) workSer;
                    map.put("work", work.value);
                }

                if (userStatusSer != null && userStatusSer instanceof ItemCatSub) {
                    userStatus = (ItemCatSub) userStatusSer;
                    map.put("userStatus", userStatus.value);
                }
                loadJianLi();
            } else if (requestCode == 10004) {
                loadJianLi();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
    }


    public void setTitleListener(RenCaiMainFragment.TitleListener titleListener) {
        this.titleListener = titleListener;
    }
}
